import {createRouter, createWebHistory} from 'vue-router'
import Login from '../views/Login.vue'

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            component: Login
        },
        {
            path: "/login",
            component: Login
        },
        {
            path: '/home',
            name: 'home',
            component: () => import('../views/Index.vue'),
            children: [
                {
                    path: '',
                    component: () => import('../views/home/Index.vue')
                },
                {
                    path: 'sysRole/index',
                    component: () => import('../views/home/children/sysRole/Index.vue')
                },
                {
                    path: 'sysUser/index',
                    component: () => import('../views/home/children/sysUser/Index.vue')
                },
                {
                    path: 'sysUser/info',
                    component: () => import('../views/home/children/userInfo/Index.vue')
                },
                {
                    path: 'sysMenu/index',
                    component: () => import('../views/home/children/sysMenu/Index.vue')
                },
            ]
        }
    ]
})

//前置路由守卫
router.beforeEach((to, from, next) => {
    let localStorageSysUserToken = localStorage.getItem("Authorization")
    if (to.path === '/login' && localStorageSysUserToken) {
        // 如果localStorage中的sysUserToken存在且访问了登录路由
        // 跳转到首页页面
        next({path: '/home'})
    } else if (to.path === '/login') {
        // 跳过登录路由/login
        next()
    } else if (!localStorageSysUserToken) {
        // 如果localStorage中的sysUserToken不存在，表示未登录
        // 跳转到登录页面
        next({path: '/login'})
    }

    // 其他正常情况，next()继续
    next()
})

export default router
